package com.JZ.QM.service.impl;

import com.JZ.QM.common.dao.TradeRecordDao;
import com.JZ.QM.common.dao.UserAccountDao;
import com.JZ.QM.common.entity.TradeRecordEntity;
import com.JZ.QM.common.entity.UserAccountEntity;
import com.JZ.QM.service.WealthAccountService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.JZ.QM.common.utils.PageUtils;
import com.JZ.QM.common.utils.Query;

import com.JZ.QM.common.dao.WealthAccountDao;
import com.JZ.QM.common.entity.WealthAccountEntity;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service
public class WealthAccountServiceImpl extends ServiceImpl<WealthAccountDao, WealthAccountEntity> implements WealthAccountService {

    @Resource
    WealthAccountDao wealthAccountDao;
    @Resource
    UserAccountDao userAccountDao;
    @Resource
    TradeRecordDao tradeRecordDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) throws Exception {
        IPage<WealthAccountEntity> page = this.page(
                new Query<WealthAccountEntity>().getPage(params),
                new QueryWrapper<WealthAccountEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 将资金从平台账号转到财富账号中
     * @param accountId
     * @param comBaseId
     * @param amount
     * @param userId
     * @return
     */
    @Transactional
    @Override
    public TradeRecordEntity transferAmount(Long accountId, Long comBaseId, BigDecimal amount,Long userId) {
        //财富账号实体
        WealthAccountEntity wealthAccountEntity = new WealthAccountEntity();
        //用户账号实体
        UserAccountEntity userAccountEntity = new UserAccountEntity();
        //交易记录实体
        TradeRecordEntity tradeRecordEntity = new TradeRecordEntity();
        //扣款flag
        int updateAccountFlag = 1;
        //转款flag
        int updateWealthAccountFlag = 1;
        //创建交易记录flag
        int saveTradeFlag = 1;

        userAccountEntity = userAccountDao.selectById(accountId);

        //先从平台账号中扣除钱款
        if(userAccountEntity != null){
            userAccountEntity.setAccountAmoount(userAccountEntity.getAccountAmoount().subtract(amount));
            updateAccountFlag = userAccountDao.updateById(userAccountEntity);
        }

        WealthAccountEntity wealthAccount = getWealthAccount(comBaseId,userId);
        //检查财富账号实体是否已经存在
        if( wealthAccount == null){

            //创建财富账号，进行转款
            wealthAccountEntity.setAccountId(accountId);
            wealthAccountEntity.setComBaseId(comBaseId);
            wealthAccountEntity.setWealthAccountAmoount(amount);
            wealthAccountEntity.setIsUpdate(0);
            wealthAccountEntity.setIsUsed(1);

            updateWealthAccountFlag = wealthAccountDao.insert(wealthAccountEntity);

        }else{
            wealthAccountEntity = wealthAccount;
            wealthAccountEntity.setWealthAccountAmoount(wealthAccountEntity.getWealthAccountAmoount().add(amount));
            wealthAccountEntity.setIsUsed(1);

            updateAccountFlag = wealthAccountDao.updateById(wealthAccountEntity);
        }

        //进行资金流水号的组装
        String timeUUid = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String logicId = "QMT" + timeUUid;

        //创建资金流水
        tradeRecordEntity.setLogicId(logicId);
        tradeRecordEntity.setTradeAmoount(amount);
        //设置关联账户
        tradeRecordEntity.setRelevanceAccountId(wealthAccountEntity.getWealthAccountId());
        tradeRecordEntity.setRelevanceAccountType(2);
        //设置交易类型
        tradeRecordEntity.setTradeType(0);
        tradeRecordEntity.setTradeCategory(1);
        tradeRecordEntity.setUserId(userId);

        saveTradeFlag = tradeRecordDao.insert(tradeRecordEntity);

        if(1 == (updateAccountFlag & updateWealthAccountFlag & saveTradeFlag)){
            return tradeRecordEntity;
        }else {
            return null;
        }
    }

    /**
     * 获取财富账号实体
     * @param comBaseId
     * @return
     */
    @Override
    public WealthAccountEntity getWealthAccount(Long comBaseId, Long userId) {
        //平台账号条件查询器
        QueryWrapper<UserAccountEntity> userAccountQueryWarpper = new QueryWrapper<>();
        //财富账号条件查询器
        QueryWrapper<WealthAccountEntity> wealthAccountQueryWrapper = new QueryWrapper<>();
        //用户账号实体类
        UserAccountEntity userAccountEntity = new UserAccountEntity();
        //财富账户实体
        WealthAccountEntity wealthAccountEntity = new WealthAccountEntity();

        userAccountQueryWarpper.eq("user_id",userId);
        userAccountEntity = userAccountDao.selectOne(userAccountQueryWarpper);

        wealthAccountQueryWrapper.eq("com_base_id",comBaseId)
                    .eq("account_id",userAccountEntity.getAccountId());

        wealthAccountEntity = wealthAccountDao.selectOne(wealthAccountQueryWrapper);

        return wealthAccountEntity;
    }


    /**
     * 将资金从财富账号转到平台账号中
     * @param wealthAccountId
     * @param userId
     * @param tradeCategory 3 表示撤单成功  4  表示赎回成功
     * @return
     */
    @Override
    public TradeRecordEntity transferBackAmount(Long wealthAccountId,Long userId,Integer tradeCategory,Long tradeId) {
        //财富账号实体
        WealthAccountEntity wealthAccountEntity = new WealthAccountEntity();
        //用户账号实体
        UserAccountEntity userAccountEntity = new UserAccountEntity();
        //交易记录实体
        TradeRecordEntity tradeRecordEntity = new TradeRecordEntity();
        //转款金额
        BigDecimal amount = BigDecimal.valueOf(0);
        //转款flag
        int updateAccountFlag = 0;
        //扣款flag
        int updateWealthAccountFlag = 0;
        //创建交易记录flag
        int saveTradeFlag = 0;

        wealthAccountEntity = wealthAccountDao.selectById(wealthAccountId);

        if(wealthAccountEntity != null){
            //财富账户进行扣款
            amount = wealthAccountEntity.getWealthAccountAmoount();
            wealthAccountEntity.setWealthAccountAmoount(BigDecimal.valueOf(0));

            updateWealthAccountFlag = wealthAccountDao.updateById(wealthAccountEntity);
        }

        userAccountEntity = userAccountDao.selectById(wealthAccountEntity.getAccountId());

        if(userAccountEntity != null){
            //平台账户转款
            userAccountEntity.setAccountAmoount(userAccountEntity.getAccountAmoount().add(amount));

            updateAccountFlag = userAccountDao.updateById(userAccountEntity);
        }

        tradeRecordEntity = tradeRecordDao.selectById(tradeId);
        tradeRecordEntity.setTradeCategory(tradeCategory);

        saveTradeFlag = tradeRecordDao.updateById(tradeRecordEntity);

        if(1 == (saveTradeFlag & updateAccountFlag & updateWealthAccountFlag)){
            return tradeRecordEntity;
        }else {
            return null;
        }
    }
}